package com.pirestupppai.ui.activity;

import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pirestupppai.R;
import com.pirestupppai.adapter.FragmentAdapter;
import com.pirestupppai.base.BaseActivity;
import com.pirestupppai.bean.TagItem;
import com.pirestupppai.common.Constant;
import com.pirestupppai.network.NetworkRequest;
import com.pirestupppai.network.TupaiSubscriber;
import com.pirestupppai.rxbus.RxBus;
import com.pirestupppai.ui.fragment.SearchTagFragment;
import com.pirestupppai.ui.fragment.SearchUserFragment;
import com.pirestupppai.utils.SharedPreferenceUtil;
import com.pirestupppai.utils.Utils;
import com.pirestupppai.widgets.helper.TabLayoutHelper;
import com.pirestupppai.widgets.view.FlowTagLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static com.pirestupppai.rxbus.RxBus.RXBUS_SEARCH;

/**
 * 搜索页
 *
 * @author: xiaoluo
 * @date: 2017-04-11 14:39
 */
public class SearchActivity extends BaseActivity {

    @BindView(R.id.search_tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.search_viewpager)
    ViewPager viewPager;
    @BindView(R.id.search_btn)
    TextView searchBtn;
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_popular_layout)
    FlowTagLayout popularLayout;
    @BindView(R.id.search_history_layout)
    FlowTagLayout historyLayout;
    @BindView(R.id.default_layout)
    LinearLayout defaultLayout;
    @BindView(R.id.search_parent)
    LinearLayout searchParentLayout;
    @BindView(R.id.clear_history_btn)
    TextView clearBtn;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.clear_btn)
    ImageView clearEditBtn;

    private FragmentAdapter mFragmentAdapter;
    private List<String> mHistoryList = new ArrayList<>();
    private List<String> mPopularList = new ArrayList<>();

    @Override
    protected Context getActivityContext() {
        return this;
    }

    @Override
    protected int loadParentLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void initViews() {

        mFragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
        mFragmentAdapter.addFragment(new SearchTagFragment(), "标签");
        mFragmentAdapter.addFragment(new SearchUserFragment(), "用户");
        viewPager.setAdapter(mFragmentAdapter);
        viewPager.setOffscreenPageLimit(1);
        // 将TabLayout与viewpager绑定
        tabLayout.setupWithViewPager(viewPager);

        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                TabLayoutHelper.setIndicatorWidth(tabLayout, 60, 60);
            }
        });
    }

    @Override
    protected void initListeners() {
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    defaultLayout.setVisibility(View.VISIBLE);
                    viewPager.setVisibility(View.GONE);
                }
            }
        });

        clearEditBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
            }
        });

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                    Utils.showToast("请输入内容");
                    return;
                }
                saveAndSearch(searchEt.getText().toString().trim());
            }
        });

        searchParentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputPanel();
            }
        });

        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (TextUtils.isEmpty(searchEt.getText().toString().trim())) {
                        Utils.showToast("请输入内容");
                        return false;
                    }
                    saveAndSearch(searchEt.getText().toString().trim());
                    return true;
                }
                return false;
            }
        });

        clearBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                historyLayout.setVisibility(View.GONE);
                for (int i = 0; i < mHistoryList.size(); i++) {
                    SharedPreferenceUtil.editor.remove(Constant.SPKey.HISTORY_ITEM + i);
                }
                SharedPreferenceUtil.editor.putInt(Constant.SPKey.HISTORY_SIZE, 0);
                SharedPreferenceUtil.editor.apply();
                mHistoryList.clear();
                clearBtn.setText("暂无搜索记录");
                clearBtn.setEnabled(false);
            }
        });
    }

    /**
     * 保存并搜索
     */
    private void saveAndSearch(String searchKey) {
        defaultLayout.setVisibility(View.GONE);
        viewPager.setVisibility(View.VISIBLE);

        searchEt.setSelection(searchKey.length());
        hideInputPanel();

        boolean isInHistory = false;
        if (mHistoryList.size() != 0) {
            for (int i = 0; i < mHistoryList.size(); i++) {
                if (searchKey.equals(mHistoryList.get(i))) {
                    isInHistory = true;
                    mHistoryList.remove(i);
                    mHistoryList.add(0, searchKey);
                    break;
                }
            }
        }

        if (!isInHistory) {
            if (mHistoryList.size() >= 10) {
                mHistoryList.remove(mHistoryList.size() - 1);
            }
            mHistoryList.add(0, searchKey);
        }

        SharedPreferenceUtil.editor.putInt(Constant.SPKey.HISTORY_SIZE, mHistoryList.size());
        for (int i = 0; i < mHistoryList.size(); i++) {
            SharedPreferenceUtil.editor.remove(Constant.SPKey.HISTORY_ITEM + i);
            SharedPreferenceUtil.editor.putString(Constant.SPKey.HISTORY_ITEM + i, mHistoryList.get(i));
        }
        SharedPreferenceUtil.editor.apply();

        RxBus.getInstance().post(RXBUS_SEARCH, searchKey);
    }

    @Override
    protected void initLogic() {
        loadHistoryData();
        loadPopularData();
    }


    /**
     * 获取历史数据
     */
    private void loadHistoryData() {
        mHistoryList.clear();
        int historySize = SharedPreferenceUtil.sp.getInt(Constant.SPKey.HISTORY_SIZE, 0);
        if (historySize <= 0) {
            return;
        }

        clearBtn.setText("清除历史记录");
        clearBtn.setEnabled(true);
        for (int i = 0; i < historySize; i++) {
            mHistoryList.add(SharedPreferenceUtil.sp.getString(Constant.SPKey.HISTORY_ITEM + i, null));
        }

        LinearLayout.LayoutParams tagLp = new LinearLayout.LayoutParams(
                WRAP_CONTENT, WRAP_CONTENT);
        tagLp.setMargins(Utils.dpToPx(mContext, 0), Utils.dpToPx(mContext, 5),
                Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 5));
        for (int i = 0; i < mHistoryList.size(); i++) {
            final TextView tag = new TextView(mContext);
            tag.setText(mHistoryList.get(i));
            tag.setTextSize(13);
            tag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9));
            tag.setTextColor(getResources().getColor(R.color.gray_text));
            tag.setBackgroundResource(R.drawable.selector_search_flow_tag);
            tag.setClickable(true);
            tag.setTag(tag.getText().toString());

            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchEt.setText((String) tag.getTag());
                    saveAndSearch((String) tag.getTag());
                }
            });

            historyLayout.addView(tag, tagLp);
        }
    }

    /**
     * 获取热搜数据
     */
    private void loadPopularData() {
        if (Constant.popularTags != null && Constant.popularTags.size() != 0) {
            createPopularView();
        } else {
            NetworkRequest.getInstance().getHomeTagList(1, 10,
                    new TupaiSubscriber<List<TagItem>>(mContext) {
                        @Override
                        protected void requestSuccess(List<TagItem> tagItems) {
                            if (tagItems != null && tagItems.size() != 0) {
                                for (int i = 0; i < tagItems.size(); i++) {
                                    mPopularList.add(tagItems.get(i).getText());
                                }
                                Constant.popularTags.addAll(mPopularList);
                                createPopularView();
                            }
                        }

                        @Override
                        protected void requestError(String error) {

                        }
                    });
        }
    }

    private void createPopularView() {
        if (Constant.popularTags == null || Constant.popularTags.size() == 0) {
            return;
        }
        LinearLayout.LayoutParams tagLp = new LinearLayout.LayoutParams(
                WRAP_CONTENT, WRAP_CONTENT);
        tagLp.setMargins(Utils.dpToPx(mContext, 0), Utils.dpToPx(mContext, 0),
                Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 10));
        for (int i = 0; i < Constant.popularTags.size(); i++) {
            final TextView tag = new TextView(mContext);
            tag.setText(Constant.popularTags.get(i));
            tag.setTextSize(13);
            tag.setPadding(Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9), Utils.dpToPx(mContext, 10), Utils.dpToPx(mContext, 9));
            tag.setTextColor(getResources().getColor(R.color.gray_text));
            tag.setBackgroundResource(R.drawable.selector_search_flow_tag);
            tag.setClickable(true);
            tag.setTag(tag.getText().toString());

            tag.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    searchEt.setText((String) tag.getTag());
                    saveAndSearch((String) tag.getTag());
                }
            });

            popularLayout.addView(tag, tagLp);
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 隐藏键盘
     */
    private void hideInputPanel() {
        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchEt.getWindowToken(), 0);
    }
}
